const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::staff');
const router = require('koa-router')();
exports = module.exports = router;
const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;

const user_service = require(global.prefixPath + '/services/user');

router.get('/users', async (ctx, next) => {

	ctx.checkQuery('q').notEmpty("query param is missing!").isJSON("param must be a json string!");

	if (ctx.errors) {
		ctx.status = 400;
		ctx.body = ctx.errors;
		return;
	}

	let q = JSON.parse(ctx.query.q);

	try {
		let result = await user_service.find(q);
		ctx.body = result;
	} catch (err) {
		throw err;
	}

});

/**
 *
 */
router.get('/user/:id', async (ctx, next) => {
	try {
		let user_id = ctx.params.id;
		let result = await user_service.findById(user_id);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 添加会员
 */
router.post('/user', async (ctx, next) => {
	try {
		let user = ctx.request.body;
		let result = await user_service.insert(user);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 会员注册
 */
router.post('/user/regist', async (ctx, next) => {
	try {
		let user = ctx.request.body;
		let result = await user_service.insert(user);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 修改会员
 */
router.put('/user/:username', async (ctx, next) => {
	try {
		let user_name = ctx.params.username;
		let user = ctx.request.body;
		let new_user_name = user.newusername;

		if (new_user_name && new_user_name != user_name) {
			return ctx.body = {
				ok: 0,
				msg: '用户名不可修改'
			};
			var originUser = await user_service.findByName(new_user_name);

			if (originUser) {
				return ctx.body = {
					ok: 0,
					msg: '要更新的用户名已存在'
				};
			}
			delete user.newusername;
		}


		// user._id = new ObjectId(user_id);
		let result = await user_service.findAndModify({username: user_name}, user);
		ctx.body = result;
	} catch (err) {

		console.log('err: ', err);
		throw err;
	}
});
/**
 * 收藏信息
 */
router.put('/user/:id/:userid/collection', async (ctx, next) => {
    try {
        let info_id = ctx.params.id;
        let user_id = ctx.params.userid;
        let oid = new ObjectId(info_id);
        let uid = new ObjectId(user_id);
        let update = {
            query: {_id: uid},
            update: {
            	$push: {pub: oid}
            }
        };
        let result = await user_service.findAndModify(update.query, update.update);
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});
/**
 * 删除会员
 */
router.delete('/user/:id', async (ctx, next) => {
	try {
		let user_id = ctx.params.id;
		let result = await user_service.delById(user_id);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});
/**
 * 删除收藏
 */
router.delete('/user/:id/:pid/delcollect', async (ctx, next) => {
	try {
		let info_id = ctx.params.pid.split(',');
		console.log('输出info_id=')
		console.log(ctx.params.pid);
		console.log(info_id)
        let user_id = ctx.params.id;
        let oid = [];
		for (var i = 0; i < info_id.length; i++) {
			oid[i] = new ObjectId(info_id[i]);
		}
        let uid = new ObjectId(user_id);
        let update = {
            query: {_id: uid},
            update: {
            	$pull: {pub: {$in: oid}}
            }
        };
        let result = await user_service.findAndModify(update.query, update.update);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});
